package com.cysion.study

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import com.cysion.other.startActivity_ex
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ui.login.LoginActivity
import com.cysion.study.widget.UIHelper
import com.cysion.study.widget.helper.Config
import com.cysion.study.widget.helper.Util

class SplashActivity : AppCompatActivity() {


    private var mPermSettingDialog: AlertDialog? = null
    private var mPermApplyDialog: AlertDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /*requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        );// 设置全屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏*/
        setContentView(R.layout.activity_splash)
        Handler().postDelayed(
            {
                //动态申请权限
                if (!Util.isPermissionsApply(this, true)) {
                    inMain()
                }

            }, 1000
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            PERM_SETTING_APPLY_CODE -> if (!Util.isPermissionsApply(this, false)) {
                //权限已经全部申请
                if (mPermSettingDialog != null && mPermSettingDialog!!.isShowing()) {
                    mPermSettingDialog!!.dismiss()
                }
                inMain()
            }
        }
    }

    /**
     * 注册权限申请回调
     *
     * @param requestCode  申请码
     * @param permissions  申请的权限
     * @param grantResults 结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        when (requestCode) {

            Config.PERMS_APPLY_CODE -> if (!Util.isPermissionOk(grantResults)) {   //有未申请的权限
                var isCanShowApplyAgain = false
                for (i in permissions.indices) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(
                            this!!,
                            permissions[i]
                        )
                    ) {
                        //只要有一个权限显示可以弹出继续申请，则可以弹出申请权限对话框
                        isCanShowApplyAgain = true
                        break
                    }
                }
                if (isCanShowApplyAgain) {
                    //可以继续弹出权限申请
                    showPermApplyDialog()
                } else {
                    //不能够继续弹出
                    showPermSettingDialog()
                }
            } else {
                inMain()
            }
        }
    }

    /**
     * 有未申请的权限，未选择不再询问，继续弹出权限申请
     */
    private fun showPermApplyDialog() {
        mPermApplyDialog = AlertDialog.Builder(this)
            .setTitle("标题")
            .setMessage("申请权限")
            .setPositiveButton("申请") { dialogInterface, i -> Util.isPermissionsApply(this!!, true) }
            .setNegativeButton("取消") { dialogInterface, i -> finish() }
            .setCancelable(false)
            .create()
        mPermApplyDialog!!.show()
    }

    /**
     * 有未申请的权限，并选了不再询问，进入设置设置应用权限
     */
    private fun showPermSettingDialog() {
        mPermSettingDialog = AlertDialog.Builder(this)
            .setTitle("提示")
            .setMessage("申请权限")
            .setPositiveButton("去设置", null)
            .setNegativeButton("取消") { dialogInterface, i -> finish() }
            .setCancelable(false)
            .create()
        mPermSettingDialog?.show()
        //以下方式可以让alertDialog点击时不自动消失
        mPermSettingDialog?.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener {
            val intent = Intent()
            //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            intent.data = Uri.fromParts("package", packageName, null)
            startActivityForResult(intent, PERM_SETTING_APPLY_CODE)
        }
    }


    companion object {
        private val PERM_SETTING_APPLY_CODE = 10
    }

    private fun inMain() {
        var token = ACache.get(Box.context).getAsString("token")
        CLog.i("token=$token")
        ACache.get(Box.context).put("resetlogin", "0")//为1 说明 更换账号登录后 首页切到首页
        if (TextUtils.isEmpty(token)) {
            UIHelper.jump(this,LoginActivity::class.java)

            finish()
        } else {
            UserCache.token = token
            startActivity_ex<MainActivity>()
            finish()
        }
    }


}
